package org.bigk.invoices.actions.login;

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;
import org.bigk.invoices.Globals;
import org.bigk.invoices.actions.InvoicesActionSupport;
import org.bigk.invoices.exceptions.ServiceException;
import org.bigk.invoices.services.LoginService;

public class LogoutAction extends InvoicesActionSupport implements SessionAware {
	/**
	 * Logger for this class
	 */
	private static final Log logger = LogFactory.getLog(LogoutAction.class);

	private static final long serialVersionUID = 0xd421157e95b95d43L;

	private Map<String, Object> session;
	private LoginService loginService;

	@SuppressWarnings("unchecked")
	public String execute() {
		if (logger.isDebugEnabled()) {
			logger.debug("execute() - start");
		}

		try {
			int res = loginService.processLogout();
			if (res == 0) {
				addActionMessage("wylogowanie OK");
				session.put(Globals.SP_LOGGED_FLAG, Boolean.FALSE);
				if (session instanceof SessionMap) {
					try {
						((SessionMap<String, Object>) session).invalidate();
					} catch (IllegalStateException e) {
						logger.error("execute()", e);
					}
				}
			}
		} catch (ServiceException e) {
			logger.error("execute()", e);
			addActionError(getText("error.dbaccess"));

			if (logger.isDebugEnabled()) {
				logger.debug("execute() - end - return value=" + ERROR);
			}
			return ERROR;
		}

		if (logger.isDebugEnabled()) {
			logger.debug("execute() - end - return value=" + SUCCESS);
		}
		return SUCCESS;
	}

	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	public LoginService getLoginService() {
		return loginService;
	}

	public void setLoginService(LoginService loginService) {
		this.loginService = loginService;
	}
	
	
}
